package com.faklyn.bootelasticsearch.config;

import lombok.Data;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author ronghl
 * @date 2021-01-27
 */
@Data
@Configuration
public class EsClientConfig {


    //    @Bean
    public TransportClient transportClient() {
        Settings esSetting = Settings.builder()
                .put("cluster.name", "elasticsearch")
//                .put("cluster-nodes","127.0.0.1:9200")
                .put("client.transport.sniff", true)
                .put("thread_pool.search.size", 10)
                .build();
        TransportClient transportClient = new PreBuiltTransportClient(esSetting);
        TransportAddress transportAddress = null;
        try {
            transportAddress = new TransportAddress(InetAddress.getByName("localhost"), 9300);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        transportClient.addTransportAddress(transportAddress);
        return transportClient;
    }

    //    @Bean
    public ElasticsearchOperations elasticsearchOperations(TransportClient transportClient) {
        return new ElasticsearchTemplate(transportClient);
    }


    @Bean
    public Client client() {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .build();
        TransportClient client = new PreBuiltTransportClient(settings);
        try {
            client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9200));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return client;
    }


}
